iT邦幫忙

2023 iThome 鐵人賽

DAY 25
0

我們來寫三個測試

  1. 驗證給定延遲後是否有呼叫回呼函式。
  2. 驗證更改延遲是否會更改間隔。
  3. 驗證如果延遲是**null**,則不應呼叫回呼函式。
import { renderHook, act } from "@testing-library/react";
import { useInterval } from "../src";

jest.useFakeTimers();

describe("useInterval", () => {
  it("calls the callback after a given delay", () => {
    const callback = jest.fn();
    const delay = 1000;

    renderHook(() => useInterval(callback, delay));

    // Fast-forward until all timers have been executed
    act(() => {
      jest.advanceTimersByTime(delay);
    });

    expect(callback).toHaveBeenCalledTimes(1);

    act(() => {
      jest.advanceTimersByTime(delay);
    });

    expect(callback).toHaveBeenCalledTimes(2);
  });

  it("does not call the callback if delay is null", () => {
    const callback = jest.fn();

    renderHook(() => useInterval(callback, null));

    act(() => {
      jest.advanceTimersByTime(1000); // 1s for example
    });

    expect(callback).not.toHaveBeenCalled();
  });

  it("clears the previous interval and restarts with a new delay", () => {
    const callback = jest.fn();

    const { rerender } = renderHook(
      ({ delay }) => useInterval(callback, delay),
      { initialProps: { delay: 1000 } }
    );

    act(() => {
      jest.advanceTimersByTime(1000); // 1s for the initial delay
    });

    expect(callback).toHaveBeenCalledTimes(1);

    // Now, change the delay
    rerender({ delay: 5000 });

    act(() => {
      jest.advanceTimersByTime(1000);
    });

    expect(callback).toHaveBeenCalledTimes(1); // Not called again after 1s, due to the new delay

    act(() => {
      jest.advanceTimersByTime(4000); // 5s total since rerender
    });

    expect(callback).toHaveBeenCalledTimes(2);
  });
});

上一篇
[Day 24] useInterval 製作
下一篇
[Day 26] 實戰時間useLogin
系列文
React進階班,用typescript與jest製作自己的custom hooks庫30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言